package com.wideplay.warp.security;

import net.jcip.annotations.NotThreadSafe;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * On: 25/09/2007
 *
 * A Filter chain impl which basically passes itself to the "current" filter and iterates
 *  thru the chain. It also proceeds to the given webapp (default) servlet filter chain.
 *
 * Instances of this class are expected to be confined to a single thread.
 *
 * @author Dhanji R. Prasanna
 * @since 1.0
 * @NotManaged
 */
@NotThreadSafe
class FilterChainInvocation implements FilterChain {
    private final List<Filter> filters;
    private final FilterChain proceedingChain;
    private int index = -1;

    public FilterChainInvocation(List<Filter> filters, FilterChain proceedingChain) {
        this.filters = filters; //do not wrap in immutable collection
        this.proceedingChain = proceedingChain;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {

        //no filters to run?
        if (filters.isEmpty())
            return;

        index++;

        //dispatch down the chain while there are more filters
        if (index < filters.size()) {
            filters.get(index).doFilter(servletRequest, servletResponse, this);
        } else
            //we've reached the end of the chain, lets dispatch to the normal filter chain and be done
            proceedingChain.doFilter(servletRequest, servletResponse);
    }
}
